$(document).ready(function(){
	var currentPage = 1;
	var pageSize = 10;
	var token = $.zui.store.get("token");
	var userId = $.zui.store.get("userId");
	
	var queryListFun = function(){
		//获取列表数据
		var queryListUrl = adminQueryUrl + devInfoService + queryPageListMethod;
		
		var param = "";
		//搜索参数
		if ($("#queryDevInfNameLike").val()!=''){
			param += "queryDevInfNameLike="+$("#queryDevInfNameLike").val();
		}
		if ($("#queryDevFactory").val()!=''){
			param += "&queryDevFactory="+$("#queryDevFactory").val();
		}
		if ($("#queryDevInfCode").val()!=''){
			param += "&queryDevInfCode="+$("#queryDevInfCode").val();
		}
		if ($("#queryDevInfStatus").val()!=''){
			param += "&queryDevInfStatus="+$("#queryDevInfStatus").val();
		}
		if ($("#queryDevModel").val()!=''){
			param += "&queryDevModel="+$("#queryDevModel").val();
		}
		if (currentPage>0){
			param += "&currentPage="+(currentPage-1);
		}
		param += "&pageSize="+pageSize;
		param += "&currentPage="+(currentPage-1);
		
		console.log('queryListUrl='+queryListUrl);
		console.log('token='+token+",userId="+userId);
		console.log('param='+param);
		$.ajax({
			url:queryListUrl,
			type:'post',
			beforeSend:function(xhr){
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{"token":token,"userId":userId},
			data:param,
			dataType:"JSON",
			success:function(result){
				console.log(result.success);
				console.log(result.pageList);
				if (result.success== '1'){
					document.getElementById("queryDevInfStatus").options.length=1;
					document.getElementById("queryDevFactory").options.length=1;
					document.getElementById("queryDevModel").options.length=1;
					$.each(result.devFactoryList, function(i, item){ 
						if(item.DevFactory_ID==result.searchMap.queryDevFactory){
							$("#queryDevFactory").append("<option value='"+item.DevFactory_ID+"' selected='selected'>"+item.DevFactoryName+"</option>");
						}else{
							$("#queryDevFactory").append("<option value='"+item.DevFactory_ID+"'>"+item.DevFactoryName+"</option>");
						}
					});
					$.each(result.devModelList, function(i, item){ 
						if(item.DevModel_ID==result.searchMap.queryDevModel){
							$("#queryDevModel").append("<option value='"+item.DevModel_ID+"' selected='selected'>"+item.DevModelName+"</option>");
						}else{
							$("#queryDevModel").append("<option value='"+item.DevModel_ID+"'>"+item.DevModelName+"</option>");
						}
					});
					$.each(result.statusList, function(i, item){ 
						if(item.key_value==result.searchMap.queryDevInfStatus){
							$("#queryDevInfStatus").append("<option value='"+item.key_value+"' selected='selected'>"+item.key_name+"</option>");
						}else{
							$("#queryDevInfStatus").append("<option value='"+item.key_value+"'>"+item.key_name+"</option>");
						}
					});
					$('#listDataGrid').empty();
					$('#listDataGrid').data('zui.datagrid',null);
					$('#listPager').empty();
					$('#listPager').data('zui.pager',null);
					
					$('#listDataGrid').datagrid({
						checkable: true,
					    checkByClickRow: true,
					    selectable: true,
					    dataSource: {
					        cols:[
					        		{name: 'DevInf_ID', label: '主键', width: 0},
					        	 	{name: 'DevInf_Code', label: '设备编码', width: 150},
						            {name: 'DevInfName', label: '设备名称', width: 134},
						            {name: 'DevFactoryName', label: '所属厂商', width: 109},
						            //{name: 'DevFactory_Code', label: '所属厂商编码', width: 109},
						            {name: 'DevModelName', label: '所属型号', width: 109},
						            //{name: 'DevModel_Code', label: '所属型号编码', width: 109},
						            {name: 'Opr_Date1', label: '操作时间', width: -1}
					        ],
					        cache:false,
					        array:result.pageList
					    }
					 
					});	
					$('#listDataGrid').data('zui.datagrid').sortBy('DevInf_ID', 'asc');
					
					// 手动进行初始化
					$('#listPager').pager({
					    page: currentPage,
					    recPerPage:pageSize,
					    elements:['first_icon', 'prev_icon', 'pages', 'next_icon', 'last_icon', 'total_text','size_menu','goto'],
					    pageSizeOptions:[5,10,20,30,50,100],
					    recTotal: result.pageTotal
					});
				}
				else {
					new $.zui.Messager(result.msg, {
					    type: 'warning', // 定义颜色主题
					    placement: 'center' // 定义显示位置
					}).show();
				}
			},
			error:function(result){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning', // 定义颜色主题
				    placement: 'center' // 定义显示位置
				}).show();
			}
		});
	};
	//调起查询数据
	queryListFun();
	
	//查询
	$("#searchBtn").click(function(){
		queryListFun();
	});
	//监听分页，修改当前页，条数
	$('#listPager').on('onPageChange', function(e, state, oldState) {
		currentPage = state.page;
		pageSize = state.recPerPage;
		queryListFun();
	});
	//初始化添加
	$("#addBtn").click(function(){
		//获取所属厂商列表
		var url = adminQueryUrl + devInfoService +initAddMethod ;
		var param = '';//请求到列表页面
		$("#addForm")[0].reset();
		console.log(url+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				if (data.success=='1'){
					document.getElementById("addDevFactory_Code").options.length=1;
					document.getElementById("addDevModel_Code").options.length=1;
					document.getElementById("addOrg_Code").options.length=1;
					$.each(data.devFactoryList, function(i, item){ 
						$("#addDevFactory_Code").append("<option value='"+item.DevFactory_ID+"'>"+item.DevFactoryName+"</option>");
					});
					$.each(data.devModelList, function(i, item){ 
						$("#addDevModel_Code").append("<option value='"+item.DevModel_ID+"'>"+item.DevModelName+"</option>");
					});
					$.each(data.devOrgList, function(i, item){ 
						$("#addOrg_Code").append("<option value='"+item.Org_ID+"'>"+item.Org_Name+"</option>");
					});
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});

		
	});
	$('#DevImage1').uploader({
	    autoUpload: true,            // 当选择文件后立即自动进行上传操作
	    url: adminQueryUrl + fileService + "?action=uploadDevImage1",  // 文件上传提交地址
	    limitFilesCount:1,
	    responseHandler: function(responseObject, file) {
	    	if (responseObject!=null && responseObject.response!=null){
	    		var resultJson = JSON.parse(responseObject.response);
	    		if (resultJson.success!=null && resultJson.success!=''
		    			&& typeof(resultJson.success)!='undefined'
	    				&& resultJson.fileName!=''
		    			&& typeof(resultJson.fileName)!='undefined'){
	    			if (resultJson.success=='1' ){
	    				$("#devimage1").val(resultJson.fileName);
	    			}
	    		}
	    	}
	    } //responseHandler
	});
	$("#addSaveBtn").click(function(){
			var validDevInfoNameUrl = adminQueryUrl + devInfoService + validDevInfo ;
			$("#addForm").validate({
				rules:{
					addDevInfName:{
						"required":true,
						"remote":{
							url:validDevInfoNameUrl,
							type:'post',
							beforeSend:function(xhr){//设置请求头信息
								xhr.setRequestHeader("token",token);
								xhr.setRequestHeader("userId",userId);
							},
							header:{'token':token,'userId':userId},
							dataType:'json',
							data:{
								'addDevInfName':function(){
									return $("#addDevInfName").val();
								}
							}
						}
					},
					addDevFactory_Code:{
						"required":true
					},
					addDevModel_Code:{
						"required":true
					},
					addOrg_Code:{
						"required":true
					}
					
				},
				messages:{
					addDevInfName:{
						"required":"请输入设备名称！",
						"remote":"该设备名称已经存在！"
					},
					addDevFactory_Code:{
						"required":"请选择设备所属厂商！"
					},
					addDevModel_Code:{
						"required":"请选择设备所属型号！"
					},
					addOrg_Code:{
						"required":"请选择设备所属机构！"
					}
				},
				submitHandler:function(form){
					console.log("xx:"+adminQueryUrl +  devInfoService + addMethod);
					
					$.ajax({
						url:adminQueryUrl + devInfoService + addMethod ,
						type:'post',
						dataType:'JSON',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						header:{'token':token,'userId':userId},
						data:$(form).serialize(),
						success:function(data){
							console.log('添加data='+data);
							if (data.success == '1') {
			                	new $.zui.Messager('添加成功!', {
			    				    type: 'success',
			    				    placement:'center'
			    				}).show();
			                	queryListFun();
			                	$('#addModal').modal('hide', 'fit');
			                }
			                else{
			                	new $.zui.Messager(data.msg, {
			    				    type: 'warning',
			    				    placement:'center'
			    				}).show();
			                }
						},
						error:function(e){
							new $.zui.Messager('系统繁忙,请稍候再试!', {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
						}
					});
				}
			});	
	    });
	//初始化修改
	$("#updateBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#updateForm")[0].reset();
			var url = adminQueryUrl + devInfoService +initUpdateMethod;
			var param = 'DevInfoId='+selectedItems[0].DevInf_ID;
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('初始化修改data='+data);
					if (data.success=='1'){
						document.getElementById("updateDevFactory_Code").options.length=1;
						document.getElementById("updateDevModel_Code").options.length=1;
						document.getElementById("updateOrg_Code").options.length=1;
						$("#updateDevInf_Code").val(data.devInfoMap.DevInf_Code);
						$("#updateDevInfName").val(data.devInfoMap.DevInfName);
						$.each(data.devFactoryList, function(i, item){ 
							if(item.DevFactory_ID==data.devInfoMap.DevFactory_Code){
								console.log(item.DevFactory_ID+"=="+data.devInfoMap.DevFactory_Code)
								$("#updateDevFactory_Code").append("<option value='"+item.DevFactory_ID+"' selected='selected'>"+item.DevFactoryName+"</option>");
							}else{
								$("#updateDevFactory_Code").append("<option value='"+item.DevFactory_ID+"'>"+item.DevFactoryName+"</option>");
							}
						});
						$.each(data.devModelList, function(i, item){ 
							if(item.DevModel_ID==data.devInfoMap.DevModel_Code){
								console.log(item.DevModel_ID+"=="+data.devInfoMap.DevModel_Code)
								$("#updateDevModel_Code").append("<option value='"+item.DevModel_ID+"' selected='selected'>"+item.DevModelName+"</option>");
							}else{
								$("#updateDevModel_Code").append("<option value='"+item.DevModel_ID+"'>"+item.DevModelName+"</option>");
							}
						});
						$.each(data.devOrgList, function(i, item){ 
							if(item.Org_ID==data.devInfoMap.Org_Code){
								console.log(item.Org_ID+"=="+data.devInfoMap.Org_Code)
								$("#updateOrg_Code").append("<option value='"+item.Org_ID+"' selected='selected'>"+item.Org_Name+"</option>");
							}else{
								$("#updateOrg_Code").append("<option value='"+item.Org_ID+"'>"+item.Org_Name+"</option>");
							}
						});
						$("#updateDevHwVer").val(data.devInfoMap.DevHwVer);
						$("#updateDevAppVer").val(data.devInfoMap.DevAppVer);
						$("#updateDevParamVer").val(data.devInfoMap.DevParamVer);
						$("#updateDevOtherVer").val(data.devInfoMap.DevOtherVer);
						$("#updatedevimage1Show").attr('src',adminQueryUrl+"/"+data.devInfoMap.DevImage1);
						$("#updatedevimage1").val(data.devInfoMap.DevImage1);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
	$('#updateDevImage1').uploader({
	    autoUpload: true,            // 当选择文件后立即自动进行上传操作
	    url: adminQueryUrl + fileService + "?action=uploadDevImage1",  // 文件上传提交地址
	    limitFilesCount:1,
	    responseHandler: function(responseObject, file) {
	    	if (responseObject!=null && responseObject.response!=null){
	    		var resultJson = JSON.parse(responseObject.response);
	    		if (resultJson.success!=null && resultJson.success!=''
		    			&& typeof(resultJson.success)!='undefined'
	    				&& resultJson.fileName!=''
		    			&& typeof(resultJson.fileName)!='undefined'){
	    			if (resultJson.success=='1' ){
	    				$("#updatedevimage1").val(resultJson.fileName);
	    				$("#updatedevimage1Show").attr('src',adminQueryUrl+"/"+resultJson.fileName);
	    			}
	    		}
	    	}
	    } //responseHandler
	});
	//修改保存
	$("#updateSaveBtn").click(function(){
		var excludeDevInfoId = $('#listDataGrid').data('zui.datagrid').getCheckItems()[0].DevInf_ID;
		console.log("修改保存的ID="+excludeDevInfoId);
		$("#excludeDevInfoId").val(excludeDevInfoId);
		var validDevInfoNameUrl = adminQueryUrl + devInfoService + validDevInfo;
		$("#updateForm").validate({
			rules:{
				updateDevInfName:{
					"required":true,
					"remote":{
						url:validDevInfoNameUrl,
						type:'post',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						header:{'token':token,'userId':userId},
						dataType:'json',
						data:{
							'updateDevInfName':function(){
								return $("#updateDevInfName").val();
							},
							'excludeDevInfoId':function(){
								return $("#excludeDevInfoId").val();
							}
						}
					}
				},
				updateDevFactory_Code:{
					"required":true
				},
				updateDevModel_Code:{
					"required":true
				},
				updateOrg_Code:{
					"required":true
				}
				
			},
			messages:{
				updateDevInfName:{
					"required":"请输入设备名称！",
					"remote":"该设备名称已经存在！"
				},
				updateDevFactory_Code:{
					"required":"请选择设备所属厂商！"
				},
				updateDevModel_Code:{
					"required":"请选择设备所属型号！"
				},
				updateOrg_Code:{
					"required":"请选择设备所属机构！"
				}
			},
			submitHandler:function(form){
				var saveUrl = adminQueryUrl + devInfoService + updateMethod;
				$.ajax({
					url:saveUrl,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token",token);
						xhr.setRequestHeader("userId",userId);
					},
					header:{'token':token,'userId':userId},
					data:$(form).serialize(),
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('修改成功!', {
		    				    type: 'success',
		    				    placement:'center'
		    				}).show();
		                	queryListFun();
		                	$('#updateModal').modal('hide', 'fit');
		                	queryListFun();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
		});
	});
	//初始化详情
	$("#detailBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#detailForm")[0].reset();
			var url = adminQueryUrl + devInfoService + detailMethod;
			var param = 'DevInfoId='+selectedItems[0].DevInf_ID;//请求到列表页面
			console.log('详情param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				header:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('详情data='+data);
					if (data.success=='1'){
						$("#detailDevInf_Code").val(data.devInfoMap.DevInf_Code);
						$("#detailDevInfName").val(data.devInfoMap.DevInfName);
						
						$.each(data.devStatusList, function(i, item){ 
							if(item.key_value==data.devInfoMap.DevInfStatus){
								$("#detailDevInfStatus").val(item.key_name);
							}
						});
						$.each(data.devFactoryList, function(i, item){ 
							if(item.DevFactory_ID==data.devInfoMap.DevFactory_Code){
								console.log(item.DevFactory_ID+"=="+data.devInfoMap.DevFactory_Code)
								$("#detailDevFactory_Code").val(item.DevFactoryName);
							}
						});
						$.each(data.devModelList, function(i, item){ 
							if(item.DevModel_ID==data.devInfoMap.DevModel_Code){
								console.log(item.DevModel_ID+"=="+data.devInfoMap.DevModel_Code)
								$("#detailDevModel_Code").val(item.DevModelName);
							}
						});
						$.each(data.devOrgList, function(i, item){ 
							if(item.Org_ID==data.devInfoMap.Org_Code){
								console.log(item.Org_ID+"=="+data.devInfoMap.Org_Code)
								$("#detailOrg_Code").val(item.Org_Name);
							}
						});
						$("#detailDevHwVer").val(data.devInfoMap.DevHwVer);
						$("#detailDevAppVer").val(data.devInfoMap.DevAppVer);
						$("#detailDevParamVer").val(data.devInfoMap.DevParamVer);
						$("#detailDevOtherVer").val(data.devInfoMap.DevOtherVer);
						$("#detaildevimage1Show").attr('src',adminQueryUrl+"/"+data.devInfoMap.DevImage1);
						$("#Opr_id").val(data.devInfoMap.Opr_id);
						$("#Opr_Date").val(data.devInfoMap.Opr_Date1);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
	//显示删除确认框
	$("#deleteBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$('#deleteModal').modal('show', 'fit');
		}
	});
	//删除菜单
	$("#deleteDevModelBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		var url = adminQueryUrl + devInfoService + deleteMethod;
		var param = 'DevInfo_ID='+selectedItems[0].DevInf_ID;//请求到列表页面
		console.log('url='+url);
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data);
				$('#deleteModal').modal('hide', 'fit');
				if (data.success=='1'){
	                	new $.zui.Messager('删除成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                	queryListFun();
				}
                else{
                	new $.zui.Messager(data.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	
});